
import MenuToggle from '../components/MenuToggle';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { X, Upload, CheckCircle, AlertCircle, Folder, Plus, File } from 'lucide-react';
import React, { useCallback, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
const UploadPage = ({ toggleSidebar }) => {
  const [uploadFiles, setUploadFiles] = useState([]);
  const [dragActive, setDragActive] = useState(false);
  const [selectedFolder, setSelectedFolder] = useState('root');

  // 模拟文件夹结构
  const folders = [
    { id: 'root', name: '根目录', path: '/' },
    { id: 'documents', name: '文档', path: '/文档' },
    { id: 'images', name: '图片', path: '/图片' },
    { id: 'videos', name: '视频', path: '/视频' },
    { id: 'work', name: '工作文件', path: '/工作文件' }
  ];

  const handleDrag = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  }, []);

  const handleDrop = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFiles(e.dataTransfer.files);
    }
  }, []);

  const handleFiles = (files) => {
    const newFiles = Array.from(files).map((file, index) => ({
      id: Date.now() + index,
      file,
      name: file.name,
      size: file.size,
      type: file.type,
      status: 'pending', // pending, uploading, completed, error
      progress: 0,
      error: null
    }));

    setUploadFiles(prev => [...prev, ...newFiles]);
    
    // 模拟上传过程
    newFiles.forEach(uploadFile => {
      simulateUpload(uploadFile.id);
    });
  };

  const simulateUpload = (fileId) => {
    setUploadFiles(prev => prev.map(file => 
      file.id === fileId ? { ...file, status: 'uploading' } : file
    ));

    let progress = 0;
    const interval = setInterval(() => {
      progress += Math.random() * 15;
      
      if (progress >= 100) {
        progress = 100;
        clearInterval(interval);
        
        // 随机决定成功或失败
        const success = Math.random() > 0.1; // 90% 成功率
        
        setUploadFiles(prev => prev.map(file => 
          file.id === fileId ? {
            ...file,
            status: success ? 'completed' : 'error',
            progress: 100,
            error: success ? null : '上传失败，请重试'
          } : file
        ));
      } else {
        setUploadFiles(prev => prev.map(file => 
          file.id === fileId ? { ...file, progress } : file
        ));
      }
    }, 200);
  };

  const removeFile = (fileId) => {
    setUploadFiles(prev => prev.filter(file => file.id !== fileId));
  };

  const retryUpload = (fileId) => {
    setUploadFiles(prev => prev.map(file => 
      file.id === fileId ? { ...file, status: 'pending', progress: 0, error: null } : file
    ));
    simulateUpload(fileId);
  };

  const clearCompleted = () => {
    setUploadFiles(prev => prev.filter(file => file.status !== 'completed'));
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'error':
        return <AlertCircle className="w-5 h-5 text-red-600" />;
      default:
        return <File className="w-5 h-5 text-material-grey-500" />;
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'completed':
        return 'text-green-600';
      case 'error':
        return 'text-red-600';
      case 'uploading':
        return 'text-blue-600';
      default:
        return 'text-material-grey-600';
    }
  };

  const completedCount = uploadFiles.filter(f => f.status === 'completed').length;
  const errorCount = uploadFiles.filter(f => f.status === 'error').length;
  const uploadingCount = uploadFiles.filter(f => f.status === 'uploading').length;

  return (
    <>
      {/* 头部工具栏 */}
      <div className="">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Upload className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    上传文件
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    拖拽文件到此处或点击选择文件上传
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Select value={selectedFolder} onValueChange={setSelectedFolder}>
                <SelectTrigger className="w-48">
                  <Folder className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {folders.map(folder => (
                    <SelectItem key={folder.id} value={folder.id}>
                      {folder.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              {completedCount > 0 && (
                <Button onClick={clearCompleted} variant="outline">
                  清除已完成
                </Button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总文件数</p>
                  <p className="text-2xl font-bold text-material-grey-900">{uploadFiles.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Upload className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">上传中</p>
                  <p className="text-2xl font-bold text-blue-600">{uploadingCount}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Upload className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已完成</p>
                  <p className="text-2xl font-bold text-green-600">{completedCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">失败</p>
                  <p className="text-2xl font-bold text-red-600">{errorCount}</p>
                </div>
                <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                  <AlertCircle className="w-6 h-6 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 上传区域 */}
        <Card className="mb-6">
          <CardContent className="p-6">
            <div
              className={`border-2 border-dashed rounded-lg p-12 text-center transition-colors ${
                dragActive
                  ? 'border-primary bg-primary/5'
                  : 'border-material-grey-300 hover:border-primary/50'
              }`}
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
            >
              <div className="w-16 h-16 mx-auto mb-4 bg-primary/10 rounded-full flex items-center justify-center">
                <Upload className="w-8 h-8 text-primary" />
              </div>
              
              <h3 className="text-lg font-medium text-material-grey-800 mb-2">
                拖拽文件到此处上传
              </h3>
              
              <p className="text-material-grey-600 mb-4">
                或者点击下方按钮选择文件
              </p>
              
              <div className="flex justify-center space-x-4">
                <Button
                  onClick={() => document.getElementById('file-input').click()}
                  className="bg-primary hover:bg-primary-600"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  选择文件
                </Button>
                
                <Button
                  onClick={() => document.getElementById('folder-input').click()}
                  variant="outline"
                >
                  <Folder className="w-4 h-4 mr-2" />
                  选择文件夹
                </Button>
              </div>
              
              <input
                id="file-input"
                type="file"
                multiple
                className="hidden"
                onChange={(e) => handleFiles(e.target.files)}
              />
              
              <input
                id="folder-input"
                type="file"
                webkitdirectory=""
                className="hidden"
                onChange={(e) => handleFiles(e.target.files)}
              />
              
              <p className="text-xs text-material-grey-500 mt-4">
                支持的文件类型：图片、文档、视频、音频等，单个文件最大 100MB
              </p>
            </div>
          </CardContent>
        </Card>

        {/* 上传列表 */}
        {uploadFiles.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span>上传列表</span>
                <span className="text-sm font-normal text-material-grey-600">
                  上传到：{folders.find(f => f.id === selectedFolder)?.path}
                </span>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <div className="divide-y divide-material-grey-200">
                {uploadFiles.map((file) => (
                  <div key={file.id} className="p-4 hover:bg-material-grey-50">
                    <div className="flex items-center space-x-4">
                      {/* 文件图标和状态 */}
                      <div className="flex-shrink-0">
                        {getStatusIcon(file.status)}
                      </div>

                      {/* 文件信息 */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between mb-1">
                          <p className="text-sm font-medium text-material-grey-800 truncate">
                            {file.name}
                          </p>
                          <span className="text-xs text-material-grey-500">
                            {formatFileSize(file.size)}
                          </span>
                        </div>

                        {/* 进度条 */}
                        {file.status === 'uploading' && (
                          <div className="mb-1">
                            <Progress value={file.progress} className="h-2" />
                          </div>
                        )}

                        {/* 状态信息 */}
                        <div className="flex items-center justify-between">
                          <span className={`text-xs ${getStatusColor(file.status)}`}>
                            {file.status === 'pending' && '等待上传'}
                            {file.status === 'uploading' && `上传中 ${Math.round(file.progress)}%`}
                            {file.status === 'completed' && '上传完成'}
                            {file.status === 'error' && (file.error || '上传失败')}
                          </span>

                          {/* 操作按钮 */}
                          <div className="flex items-center space-x-2">
                            {file.status === 'error' && (
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => retryUpload(file.id)}
                                className="text-blue-600 hover:text-blue-700 h-6 px-2"
                              >
                                重试
                              </Button>
                            )}
                            
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => removeFile(file.id)}
                              className="text-red-600 hover:text-red-700 h-6 px-2"
                            >
                              <X className="w-3 h-3" />
                            </Button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* 空状态 */}
        {uploadFiles.length === 0 && (
          <div className="text-center py-12">
            <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
              <Upload className="w-8 h-8 text-material-grey-500" />
            </div>
            <h3 className="text-lg font-medium text-material-grey-700 mb-2">
              暂无上传任务
            </h3>
            <p className="text-material-grey-500">
              拖拽文件到上方区域或点击选择文件开始上传
            </p>
          </div>
        )}
      </div>
    </>
  );
};

export default UploadPage;
